package com.xxd.rpt2.service.impl

import com.xxd.rpt2.Entity.Department
import com.xxd.rpt2.Entity.User
import com.xxd.rpt2.repository.UserRepository
import com.xxd.rpt2.service.UserService
import com.xxd.utils.JwtUtil
import org.codehaus.groovy.util.StringUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.domain.Specification
import org.springframework.stereotype.Service
import org.springframework.util.StringUtils

import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.CriteriaQuery
import javax.persistence.criteria.Path
import javax.persistence.criteria.Predicate
import javax.persistence.criteria.Root

@Service
class UserImpl implements UserService{
    @Autowired
    UserRepository userRepository
    @Override
    User getUserById(int id) {
        return userRepository.findById(id)
    }

    @Override
    Page<User> findByPage(final User user, int page, int pageSize) {
        Pageable pageable = PageRequest.of(page-1,pageSize)
        Specification<User> spec = new Specification<User>(){
            @Override
            Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                Path<String> name = root.get("name");
                Path<Department> depart = root.get("department");
                if(user.getName()){
                    Predicate predicate = criteriaBuilder.like(name,"%${user.getName()}%");
                    predicates.add(predicate)
                }
                if(user?.getDepartment()){
                    Predicate predicate = criteriaBuilder.equal(depart,user.getDepartment())
                    predicates.add(predicate)
                }
                def a = new Predicate[predicates.size()]
                return criteriaBuilder.and(predicates.toArray(a));
            }
        }
        return userRepository.findAll(spec,pageable)
    }

    @Override
    User findByName(String instr) {
        return   userRepository.findUserByCode(instr)
    }

    @Override
    String signToken(String username,String salt) {
        return JwtUtil.sign(username,salt)
    }

    @Override
    User saveUser(User user) {
        return userRepository.save(user)
    }
}
